package cn.stylefeng.guns.modular.business.frequency.transportsign.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.enums.CoreExceptionEnum;
import cn.stylefeng.guns.core.exception.CustomException;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.base.entity.BaseEntity;
import cn.stylefeng.guns.modular.business.custom.enums.BonusTypeEnum;
import cn.stylefeng.guns.modular.business.custom.enums.FinanceTypeEnum;
import cn.stylefeng.guns.modular.business.custom.enums.OrderStatusEnum;
import cn.stylefeng.guns.modular.business.custom.enums.TakeCarTypeEnum;
import cn.stylefeng.guns.modular.business.frequency.banner.config.activityMq.Producer;
import cn.stylefeng.guns.modular.business.frequency.finance.mapper.FinanceMapper;
import cn.stylefeng.guns.modular.business.frequency.finance.model.result.ExcelHeaderInfo;
import cn.stylefeng.guns.modular.business.frequency.financedetail.entity.FinanceDetail;
import cn.stylefeng.guns.modular.business.frequency.financedetail.mapper.FinanceDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.model.param.ErrorMsg;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.entity.OrderModifyDetail;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.mapper.OrderModifyDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.orderstatuschange.entity.OrderStatusChange;
import cn.stylefeng.guns.modular.business.frequency.orderstatuschange.service.OrderStatusChangeService;
import cn.stylefeng.guns.modular.business.frequency.ordersub.entity.OrderSub;
import cn.stylefeng.guns.modular.business.frequency.ordersub.mapper.OrderSubMapper;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderDTO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.OrderSignExport;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgOrderSign;
import cn.stylefeng.guns.modular.business.frequency.ordertake.mapper.OrderTakeMapper;
import cn.stylefeng.guns.modular.business.frequency.statistics.OrderSignVO;
import cn.stylefeng.guns.modular.business.frequency.syssite.entity.SysSite;
import cn.stylefeng.guns.modular.business.frequency.syssite.mapper.SysSiteMapper;
import cn.stylefeng.guns.modular.business.frequency.transport.entity.Transport;
import cn.stylefeng.guns.modular.business.frequency.transport.mapper.TransportMapper;
import cn.stylefeng.guns.modular.business.frequency.transportlevel.entity.TransportLevel;
import cn.stylefeng.guns.modular.business.frequency.transportlevel.mapper.TransportLevelMapper;
import cn.stylefeng.guns.modular.business.frequency.transportleveldetail.entity.TransportLevelDetail;
import cn.stylefeng.guns.modular.business.frequency.transportleveldetail.mapper.TransportLevelDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.transportsign.entity.TransportSign;
import cn.stylefeng.guns.modular.business.frequency.transportsign.enums.OrderSignTypeEnum;
import cn.stylefeng.guns.modular.business.frequency.transportsign.enums.TransportLevelDeliveryTypeEnum;
import cn.stylefeng.guns.modular.business.frequency.transportsign.enums.TransportStatusEnum;
import cn.stylefeng.guns.modular.business.frequency.transportsign.mapper.TransportSignMapper;
import cn.stylefeng.guns.modular.business.frequency.transportsign.model.param.DeliverySignVO;
import cn.stylefeng.guns.modular.business.frequency.transportsign.model.param.SignRecordDTO;
import cn.stylefeng.guns.modular.business.frequency.transportsign.service.TransportSignService;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.modular.business.util.poi.ExcelFormat;
import cn.stylefeng.guns.modular.business.util.poi.ExcelUtils;
import cn.stylefeng.guns.modular.util.BaseUtils;

import cn.stylefeng.guns.sys.modular.util.SnowIdUtils;
import com.alipay.api.domain.QYBMapInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.LongFunction;

/**
 * 运单签收记录表 服务实现类
 *
 * @author yujie
 * @date 2023/05/09 17:15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TransportSignServiceImpl extends ServiceImpl<TransportSignMapper, TransportSign> implements TransportSignService {

    @Resource
    private OrderSubMapper orderSubMapper;
    @Resource
    private OrderTakeMapper orderTakeMapper;
    @Resource
    private TransportLevelMapper transportLevelMapper;
    @Resource
    private OrderStatusChangeService orderStatusChangeService;
    @Resource
    private TransportLevelDetailMapper transportLevelDetailMapper;
    @Resource
    private Producer producer;
    @Resource
    private TransportMapper transportMapper;
    @Resource
    private SysSiteMapper siteMapper;
    @Resource
    private FinanceMapper financeMapper;
    @Resource
    private FinanceDetailMapper financeDetailMapper;
    @Resource
    private OrderModifyDetailMapper orderModifyDetailMapper;
    @Resource
    private BusinessUtil businessUtil;

    @Override
    public Page<PkgOrderSign> getSignRecord(SignRecordDTO orderDTO) {
        return baseMapper.getSignRecord(PageFactory.defaultPage(), orderDTO);
    }

    @Override
    public Page<OrderSignVO> getWaitSignOrderList(OrderDTO orderDTO) {
        return baseMapper.getWaitSignOrderList(PageFactory.defaultPage(), orderDTO);
    }

    @Override
    public boolean checkMultiSign(DeliverySignVO signVO, ErrorMsg errorMsg) {
        if (ObjectUtil.isNull(signVO.getTransportId()) || ObjectUtil.isNull(signVO.getOrderId())) {
            errorMsg.setErrorMsg("参数错误！");
            return false;
        }
     /*   if (signVO.getNeedMoreTransport() == null) {
            errorMsg.setErrorMsg("签收类型不可为空");
            return false;
        }*/
        // 订单状态判断是否可以签收
        TransportSign ts = baseMapper.selectOne(new QueryWrapper<TransportSign>().lambda()
                .eq(TransportSign::getOrderId, signVO.getOrderId())
                .and(wrapper -> wrapper.eq(TransportSign::getTransportId, signVO.getTransportId())));
        if (ts != null) {
            errorMsg.setErrorMsg("当前订单已经签收，请返回列表刷新后重试！");
        }
        if (OrderStatusEnum.HAS_DEPART_ORDER.status != orderSubMapper.getStatusById(signVO.getOrderId())) {
            errorMsg.setErrorMsg("当前订单已经签收，请返回列表刷新后重试！");
            return false;
        }
        return true;
    }

    @Override
    public Integer multiSign(DeliverySignVO signVO) {
        // 1.签收信息保存
        TransportSign ts = new TransportSign(SnowIdUtils.uniqueLong(), signVO.getTransportId()
                , signVO.getOrderId(), signVO.getRemark(), null, signVO.getImages(), businessUtil.getTenantId(), signVO.getSignPayType(),
                signVO.getSignGatherMoney(),
                signVO.getSignVoucher());

        // 2. 子订单修改
        OrderSub orderSubBak = orderSubMapper.selectById(signVO.getOrderId());
        OrderSub newOrderSub = new OrderSub();
        newOrderSub.setId(signVO.getOrderId());
        TransportLevel currentLevel = transportLevelMapper.getLevelByTransportIdAndOrderId(signVO.getTransportId(), signVO.getOrderId());
        //如果运单目的地和网点目的地一样,到达欠收,不一样,中专签收
        if (!ObjectUtil.equal(orderSubBak.getDestinationCode(), currentLevel.getDestinationCode())) {
            ts.setNeedMoreTransport(1);
            // 中转签收
            newOrderSub.setStatus(OrderStatusEnum.TRANSFERRING_SIGN.status);
            newOrderSub.setArriveCode(currentLevel.getDestinationCode());
            orderStatusChangeService.saveOrderStatusChange(orderSubBak.getStatus(), OrderStatusEnum.TRANSFERRING_SIGN.status, orderSubBak.getId(), "中转签收/"+orderSubBak.getArriveCode());
        } else {
            ts.setNeedMoreTransport(2);
            String remark = "";
            Integer afterStatus = null;
            // 到达签收
            int takeType = orderSubBak.getTakeType();
            if (takeType == TakeCarTypeEnum.ZI_SONG_WANG_DIAN.type || takeType == TakeCarTypeEnum.ZHI_JIAO_KE_HU.type) {
                afterStatus = OrderStatusEnum.WAIT_TAKE.status;
                remark = "签收直交客户";
                newOrderSub.setStatus(OrderStatusEnum.WAIT_TAKE.status);
                // 签收后 交付提醒

            } else {
                remark = "大板或小板运车";
                afterStatus = OrderStatusEnum.FINISHED_TRANSPORT.status;
                newOrderSub.setStatus(OrderStatusEnum.FINISHED_TRANSPORT.status);
            }
            businessUtil.addMessage(String.format("%s  %s待交付提醒", orderSubBak.getCarName(), orderSubBak.getVin()), "你有一个待交付订单，请及时处理", orderSubBak, 5);

            orderStatusChangeService.saveOrderStatusChange(orderSubBak.getStatus(), afterStatus, orderSubBak.getId(), remark);

        }
        orderSubMapper.updateById(newOrderSub);
        // 3.承运单状态修改
        int unSignedCount = transportLevelDetailMapper.countUnSignedCount(signVO.getTransportId(), signVO.getOrderId());
        int unDeliveryCount = transportLevelDetailMapper.countUnDeliveryCount(signVO.getTransportId(), signVO.getOrderId());
        if (unSignedCount == 0 && unDeliveryCount == 0) {
            transportMapper.updateStatusById(signVO.getTransportId(), TransportStatusEnum.SIGN_FINISHED.status, null);
            // 司机任务状态变更--已完成
            //supplierOrderMapper.updateStatusByTransportIdAndType(signVO.getTransportId(), 3,3);
        } else if (unSignedCount == 0 && unDeliveryCount > 0) {
            transportMapper.updateStatusById(signVO.getTransportId(), TransportStatusEnum.WAIT_DELIVERY.status, null);
        }
        // 4. 分段到达状态修改
        int levelUnSignedCount = transportLevelDetailMapper.countLevelUnSigned(currentLevel.getId(), signVO.getOrderId());
        if (levelUnSignedCount == 0) {
            transportLevelMapper.updateArrivedStatus(currentLevel.getId());
        }
        // 5.如果是到达签收
        if (ObjectUtil.equal(orderSubBak.getDestinationCode(), currentLevel.getDestinationCode())) {
            if (orderSubBak.getDeliveryPayFee() != null && orderSubBak.getDeliveryPayFee()
                    .compareTo(BigDecimal.ZERO) > 0) {
                String deliverySettlementName = "";
                String deliverySettlementPhone = "";
                Long deliverySettlementId = null;
                //不为网点中转
                if (currentLevel.getType() != 2) {
                    FinanceDetail deliveryFd = new FinanceDetail();
                    if (currentLevel.getType() == 1 || currentLevel.getType() == 3) {
                        // 网点
                        if (ObjectUtil.isNotNull(currentLevel.getSiteId())) {
                            deliverySettlementName = LoginContextHolder.me().getSysLoginUser().getName();
                            deliverySettlementPhone = LoginContextHolder.me().getSysLoginUser().getPhone();
                            deliverySettlementId = LoginContextHolder.me().getSysLoginUserId();
                            deliveryFd.setSettlementSiteId(currentLevel.getSiteId());
                        }
                    } else {
                        TransportLevel transportlevel = transportLevelMapper.getLevelByTransportIdAndOrderId(currentLevel.getTransportId(), signVO.getOrderId());
                        deliverySettlementName = transportlevel.getSettlementName();
                        deliverySettlementPhone = transportlevel.getSettlementPhone();
                        deliverySettlementId = transportlevel.getSettlementId();
                    }
                    financeMapper.updateDeliveryInfo(signVO.getOrderId(), deliverySettlementName, deliverySettlementPhone);
                    // 解决订单欠付改到付financeDetail 已经存在记录，只是结算人是空
                    FinanceDetail financeDetail = financeDetailMapper.getByOrderIdAndType(signVO.getOrderId(), 2);

                    /**
                     * 网点中转和网点附件 结算人是到达网点签收订单的人
                     * 直交用户和无网点中转,结算人是发运运单时公司垫付或者网点垫付填写的人
                     */
                    if (financeDetail == null) {
                        deliveryFd.setOrderId(signVO.getOrderId());
                        deliveryFd.setType(FinanceTypeEnum.DELIVERY.type);
                        deliveryFd.setSettlementUser(deliverySettlementName);
                        deliveryFd.setSettlementPhone(deliverySettlementPhone);
                        deliveryFd.setSettlementUserId(deliverySettlementId);
                        deliveryFd.setNeedSettlement(orderSubBak.getDeliveryPayFee());
                        deliveryFd.setUnSettlement(orderSubBak.getDeliveryPayFee());
                        deliveryFd.setHasSettlement(BigDecimal.ZERO);
                        financeDetailMapper.insert(deliveryFd);
                    } else {
                        financeDetail.setSettlementUser(deliverySettlementName);
                        financeDetail.setSettlementUserId(deliverySettlementId);
                        financeDetail.setSettlementPhone(deliverySettlementPhone);
                        financeDetailMapper.updateSettlementUserInfo(signVO.getOrderId(), 2, deliverySettlementName, deliverySettlementPhone, deliverySettlementId);
                    }
                    // ----------END-------------------------------------
                }
            }
        }
        baseMapper.insert(ts);
        // activemq通知下游业务系统
        //producer.sendBonus(BonusTypeEnum.SIGN.type, signVO.getOrderId(), LoginContextHolder.me().getSysLoginUserId());

        return ts.getNeedMoreTransport();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reMultiSign(Long orderId) {
        //回退签收
        OrderStatusChange orderStatusChange = orderStatusChangeService.getOne(new QueryWrapper<OrderStatusChange>().lambda()
                .eq(OrderStatusChange::getOrderId,orderId)
                .orderByDesc(BaseEntity::getCreateTime)
                .last("limit 1"));


        if (orderStatusChange==null||orderStatusChange.getBeforeChangeStatus()!=OrderStatusEnum.HAS_DEPART_ORDER.status){
            throw new CustomException(CoreExceptionEnum.ORDER_CHANGE_STAGE_ERROR);
        }
        //中转签收
        if ("大板或小板运车".equals(orderStatusChange.getRemark())){
            //修改订单状态
            orderSubMapper.updateStatusById(orderId,orderStatusChange.getBeforeChangeStatus(),orderStatusChange.getAfterChangeStatus());
            //到达签收
        }else if ("签收直交客户".equals(orderStatusChange.getRemark())){
            //修改订单状态
            orderSubMapper.updateStatusById(orderId,orderStatusChange.getBeforeChangeStatus(),orderStatusChange.getAfterChangeStatus());
            //直交客户
        } else  {
            if(StringUtils.isNotEmpty(orderStatusChange.getRemark())){
                String[] split = orderStatusChange.getRemark().split("/");
                OrderSub orderSub = new OrderSub();
                orderSub.setArriveCode(split[1]);
                orderSub.setId(orderId);
                orderSub.setStatus(orderStatusChange.getBeforeChangeStatus());
                orderSubMapper.updateById(orderSub);
            }

        }
        //获取最新的一条签收记录
        TransportSign transportSign = this.getOne(new QueryWrapper<TransportSign>().lambda().eq(TransportSign::getOrderId,orderId)
                .orderByDesc(BaseEntity::getCreateTime).last("limit 1 "));
        if (transportSign!=null){
            this.removeById(transportSign.getId());
        }
        //获取该订单最新的一条运单
        TransportLevelDetail levelDetail = transportLevelDetailMapper.getLastTransportLevelDetail(orderId);
        if(levelDetail!=null){
            // 3.承运单状态修改
            int unSignedCount = transportLevelDetailMapper.countUnSignedCount(levelDetail.getTransportId(), orderId);
            int unDeliveryCount = transportLevelDetailMapper.countUnDeliveryCount(levelDetail.getTransportId(), orderId);
            if (unSignedCount == 0 && unDeliveryCount == 0) {
                transportMapper.updateStatusById(levelDetail.getTransportId(), TransportStatusEnum.SIGN_FINISHED.status, null);
                // 司机任务状态变更--已完成
                //supplierOrderMapper.updateStatusByTransportIdAndType(signVO.getTransportId(), 3,3);
            } else if (unSignedCount == 0 && unDeliveryCount > 0) {
                transportMapper.updateStatusById(levelDetail.getTransportId(), TransportStatusEnum.WAIT_DELIVERY.status, null);
            }
            // 4. 分段到达状态修改
            int levelUnSignedCount = transportLevelDetailMapper.countLevelUnSigned(levelDetail.getId(),orderId);
            if (levelUnSignedCount == 0) {
                transportLevelMapper.updateArrivedStatus(levelDetail.getId());
            }
        }

    }
    @Autowired
    private HttpServletResponse response;

    @Override
    public void getExportSignRecord(SignRecordDTO orderDTO) {
        List<PkgOrderSign> list = baseMapper.getExportSignRecord(orderDTO);
        List<OrderSignExport> listExport = new ArrayList<>();
        list.forEach(item -> {
            OrderSignExport vo = new OrderSignExport();
            BeanUtils.copyProperties(item, vo);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            vo.setCreateTime(sdf.format(item.getCreateTime()));
            if (vo.getOrderCreateTime() != null) {
                vo.setOrderCreateTime(sdf.format(vo.getOrderCreateTime()));
            }
            vo.setNeedMoreTransport(item.getNeedMoreTransport() == 1 ? "中转签收":"到达签收");
            vo.setTransportType(item.getTransportType() == null ? "" : item.getTransportType() == 1 ? "公路运输":"铁路运输");
            listExport.add(vo);
        });
        List<ExcelHeaderInfo> headerInfos = Arrays.asList(new ExcelHeaderInfo(0, 1, 0, 23, "对账单"));
        ExcelUtils excelUtils = new ExcelUtils(listExport, getHeadInfo(), headerInfos, getFormatInfo());
        excelUtils.sendHttpResponse(response, "签收记录导出", excelUtils.getWorkbook());
    }


    private Map<String, ExcelFormat> getFormatInfo() {
        Map<String, ExcelFormat> format = new HashMap<>();
        format.put("createTime", ExcelFormat.FORMAT_DATE);
        format.put("orderCreateTime", ExcelFormat.FORMAT_DATE);
        format.put("deliveryPayFee", ExcelFormat.FORMAT_NUMBER);
        format.put("transportFee", ExcelFormat.FORMAT_NUMBER);
        return format;
    }


    private List<ExcelHeaderInfo> getHeadInfo() {
        return Arrays.asList(
                new ExcelHeaderInfo(3, 3, 0, 0, "订单号"),
                new ExcelHeaderInfo(3, 3, 1, 1, "签收类型"),
                new ExcelHeaderInfo(3, 3, 2, 2, "签收人"),
                new ExcelHeaderInfo(3, 3, 3, 3, "签收时间"),
                new ExcelHeaderInfo(3, 3, 4, 4, "制单人"),
                new ExcelHeaderInfo(3, 3, 5, 5, "制单时间"),
                new ExcelHeaderInfo(3, 3, 6, 6, "订单出发地"),
                new ExcelHeaderInfo(3, 3, 7, 7, "订单目的地"),
                new ExcelHeaderInfo(3, 3, 8, 8, "车辆名称"),
                new ExcelHeaderInfo(3, 3, 9, 9, "车架号"),
                new ExcelHeaderInfo(3, 3, 10, 10, "运输方式"),
                new ExcelHeaderInfo(3, 3, 11, 11, "委托方"),
                new ExcelHeaderInfo(3, 3, 12, 12, "委托方联系人"),
                new ExcelHeaderInfo(3, 3, 13, 13, "委托方联系人电话"),
                new ExcelHeaderInfo(3, 3, 14, 14, "到付金额"),
                new ExcelHeaderInfo(3, 3, 15, 15, "承运费")
        );
    }


    @Override
    public boolean checkSignUpdate(TransportSign orderSign, ErrorMsg errorMsg) {
        // 原来的签收类型
        TransportSign originSign = baseMapper.selectById(orderSign.getId());
        int orderStatus = orderSubMapper.getStatusById(originSign.getOrderId());
        if (originSign.getNeedMoreTransport() == OrderSignTypeEnum.TRANSFER_SIGN.type && orderSign.getNeedMoreTransport() == OrderSignTypeEnum.DELIVERY_SIGN.type) {
            // 中转签收改到达签收 只有订单状态为中转待发的可以更改
            if (orderStatus != OrderStatusEnum.TRANSFERRING_SIGN.status) {
                errorMsg.setErrorMsg("当前订单状态不可修为到达签收");
                return false;
            }
        } else if (originSign.getNeedMoreTransport() == OrderSignTypeEnum.DELIVERY_SIGN.type && orderSign.getNeedMoreTransport() == OrderSignTypeEnum.TRANSFER_SIGN.type) {
            // 到达签收改中转签收 只有订单状态为待送车||待交付的可以更改
            if (orderStatus != OrderStatusEnum.FINISHED_TRANSPORT.status && orderStatus != OrderStatusEnum.WAIT_TAKE.status) {
                errorMsg.setErrorMsg("当前订单状态不可修改为中转签收");
                return false;
            } else {
                // 待交付的如果有送车则不可修改
                if (orderStatus == OrderStatusEnum.WAIT_TAKE.status) {
                    int count = orderTakeMapper.countByOrderId(originSign.getOrderId());
                    if (count > 0) {
                        errorMsg.setErrorMsg("当前订单已指派送车，不可修改签收方式");
                        return false;
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void updateSign(TransportSign orderSign) {
        TransportSign originSign = baseMapper.selectById(orderSign.getId());
        OrderSub orderSub = orderSubMapper.selectById(originSign.getOrderId());
        // 签收信息更新
        baseMapper.updateById(orderSign);
        if (originSign.getNeedMoreTransport() == OrderSignTypeEnum.TRANSFER_SIGN.type) {
            if (orderSign.getNeedMoreTransport() == OrderSignTypeEnum.DELIVERY_SIGN.type) {
                //中转签收改到达签收
                // 子订单状态修改
                if (orderSub.getTakeType() == TakeCarTypeEnum.ZI_SONG_WANG_DIAN.type || orderSub.getTakeType() == TakeCarTypeEnum.ZHI_JIAO_KE_HU.type) {
                    orderSubMapper.updateStatusById(originSign.getOrderId()
                            , OrderStatusEnum.WAIT_TAKE.status, null);
                } else {
                    orderSubMapper.updateStatusById(originSign.getOrderId()
                            , OrderStatusEnum.FINISHED_TRANSPORT.status, null);
                }
                // 到付结算人添加
                //OrderSub os = orderSubMapper.selectById(orderSign.getOrderId());
                if (orderSub.getDeliveryPayFee() != null && orderSub.getDeliveryPayFee()
                        .compareTo(BigDecimal.ZERO) > 0) {
                    String deliverySettlementName = "";
                    String deliverySettlementPhone = "";
                    Long settlementUserId = null;
                    TransportLevel level = transportLevelMapper.getLevelByTransportIdAndOrderId(originSign.getTransportId(), orderSign.getOrderId());
                    Transport transport = transportMapper.selectOne(new QueryWrapper<Transport>().lambda()
                            .eq(Transport::getId, originSign.getTransportId()));
                    if (level != null && level.getType() != TransportLevelDeliveryTypeEnum.CUSTOMER.type) {
                        if (level.getType() == TransportLevelDeliveryTypeEnum.SITE.type || level.getType() == TransportLevelDeliveryTypeEnum.NEAR_SITE.type) {
                            // 网点 || 网点附近
                            if (ObjectUtil.isNotNull(level.getSiteId())) {
                                SysSite site = siteMapper.selectById(level.getSiteId());
                                deliverySettlementName = site.getName();
                                deliverySettlementPhone = site.getPhone();
                                settlementUserId = site.getId();
                            }
                        } else {
                            deliverySettlementName = transport.getSettlementUser();
                            deliverySettlementPhone = transport.getSettlementPhone();
                            settlementUserId = transport.getSettlementId();
                        }
                        financeMapper.updateDeliveryInfo(originSign.getOrderId(), deliverySettlementName, deliverySettlementPhone);
                        // 解决订单欠付改到付financeDetail 已经存在记录，只是结算人是空
                        FinanceDetail financeDetail = financeDetailMapper.getByOrderIdAndType(orderSign.getOrderId(), 2);
                        if (financeDetail == null) {
                            FinanceDetail deliveryFd = new FinanceDetail();
                            deliveryFd.setOrderId(orderSign.getOrderId());
                            deliveryFd.setType(FinanceTypeEnum.DELIVERY.type);
                            deliveryFd.setSettlementUser(deliverySettlementName);
                            deliveryFd.setSettlementPhone(deliverySettlementPhone);
                            deliveryFd.setSettlementUserId(settlementUserId);
                            deliveryFd.setNeedSettlement(orderSub.getDeliveryPayFee());
                            deliveryFd.setUnSettlement(orderSub.getDeliveryPayFee());
                            deliveryFd.setHasSettlement(BigDecimal.ZERO);
                            financeDetailMapper.insert(deliveryFd);
                        } else {
                            financeDetail.setSettlementUser(deliverySettlementName);
                            financeDetail.setSettlementUserId(settlementUserId);
                            financeDetail.setSettlementPhone(deliverySettlementPhone);
                            financeDetailMapper.updateSettlementUserInfo(orderSign.getOrderId(), 2, deliverySettlementName, deliverySettlementPhone, settlementUserId);
                        }
                        // ----------END-------------------------------------
                    }
                }
            }
        } else {
            if (orderSign.getNeedMoreTransport() == 1) {
                // 到达签收改中转签收
                // 子订单状态修改
                orderSubMapper.updateStatusById(originSign.getOrderId(), OrderStatusEnum.TRANSFERRING_SIGN.status, null);
                // 上一次发运的到达地
                //PkgTransportLevelDetailSimple tld = transportLevelDetailMapper.getPkgTransportLevelDetailSimpleByOrderIdAndTransportId(orderSign.getOrderId(), orderSign.getTransportId());
                //orderSubV2Mapper.updateArriveCode(tld.getDestinationCode(), orderSign.getOrderId());
                // 到付财务明细删除
                financeMapper.clearDeliveryCollectionInfo(originSign.getOrderId());
                financeDetailMapper.deleteByOrderIdAndType(originSign.getOrderId(), FinanceTypeEnum.DELIVERY.type);
            }
        }
        // 订单修改明细添加
        addOrderModifyDetail(originSign, orderSign);

    }

    private void addOrderModifyDetail(TransportSign origin, TransportSign now) {
        List<OrderModifyDetail> list = new ArrayList<>();
        Long orderId = origin.getOrderId();
        Long transportId = origin.getTransportId();
        Long userId = LoginContextHolder.me().getSysLoginUserId();
        if (BaseUtils.neCompareTwo(origin.getNeedMoreTransport(), now.getNeedMoreTransport())) {
            list.add(new OrderModifyDetail(orderId, transportId, "need_more_transport", "签收类型", now.getNeedMoreTransport().toString(), origin.getNeedMoreTransport().toString(), userId));
        }
        if (BaseUtils.neCompareTwo(origin.getRemark(), now.getRemark())) {
            list.add(new OrderModifyDetail(orderId, transportId, "remark", "签收备注", now.getRemark(), origin.getRemark(), userId));
        }
        if (list.size() > 0) {
            for (OrderModifyDetail orderModifyDetail : list) {
                orderModifyDetailMapper.insert(orderModifyDetail);
            }
        }
    }


}